import AStarFinder from "./AStar/AStarFinder";

/**
* @ name:cubectrl
* @ desc:自动创建说明
* @ user:By nuolo
* @ data: 2021-01-14 16:53
*/
export default class cubectrl extends Laya.Script3D {

   
    onAwake() {
        
    }

    onEnable() {
        
    }

    onStart() {
        
    }   

    onUpdate() {
        
        this.AgentUpdate();
    }

   //寻路
    private m_AstarlistPath: Laya.Vector3[] = [];
    private m_AstarIndex: number = 0;
    public m_AgentSpeed = 0.05;
    private m_finalPosition: Laya.Vector3 = new Laya.Vector3(0, 0, 0);
    private m_upVector3: Laya.Vector3 = new Laya.Vector3(0, 1, 0);
    private m_rotation2: Laya.Vector3 = new Laya.Vector3(0, 180, 0);

    private PositionValue: Laya.Vector3 = new Laya.Vector3();

    

    public Agent(vet: Laya.Vector3) {
        this.PositionValue = (this.owner as Laya.Sprite3D).transform.position;
        this.m_AstarlistPath = AStarFinder.GetInstance().Search(this.PositionValue,vet);
        this.m_AstarIndex = 0;
        this.m_AgentSpeed = 10*Laya.timer.delta/1000;
        console.log("移动速度",this.m_AgentSpeed)
    }
    //寻路 移动
    public AgentUpdate() {
        if ( this.m_AstarlistPath.length>0) {
            if (this.m_AstarIndex >= this.m_AstarlistPath.length) {
                this.m_AstarlistPath.length = 0;
                this.onAgentGoToEnd();
                return;
            }

            this. m_finalPosition = this.m_AstarlistPath[this.m_AstarIndex];
            let curdistance = Laya.Vector3.distance(this.PositionValue, this.m_finalPosition);
            if (curdistance<=1) {
                this.m_AstarIndex += 1;
            }
            let outpos = new Laya.Vector3();
            Laya.Vector3.lerp(this.PositionValue, this.m_finalPosition, this.m_AgentSpeed, outpos);
            // this.PositionValue = outpos;
            outpos.y = this.PositionValue.y;
            (this.owner as Laya.Sprite3D).transform.lookAt(outpos, this.m_upVector3, false);
            //因为资源规格,这里需要旋转180度
             (this.owner as Laya.Sprite3D).transform.rotate(this.m_rotation2, false, false);
            (this.owner as Laya.Sprite3D).transform.position = outpos;
        }
    }

    private onAgentGoToEnd() {
        console.log("导航结束");
    }
}